package sporteam.web.server;

import java.io.IOException;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sporteam.common.PMF;
import sporteam.web.client.AEuser;
import sporteam.web.client.UserAppData;

import com.restfb.DefaultFacebookClient;
import com.restfb.FacebookClient;

@SuppressWarnings("serial")
public class DisplayCompetition extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String access_token = req.getParameter("access_token");
		// Connect to facebook and retrive a user facebook (REST)
		FacebookClient facebookClient = new DefaultFacebookClient(access_token); // establish
																					// connection
																					// with
																					// facebook-graph
																					// API
																					// with
																					// a
																					// specific
																					// access_token
		com.restfb.types.User facebook_user = facebookClient.fetchObject("me",
				com.restfb.types.User.class); // me - the facebook user logged
												// in ATM.

		// retrieve user from DB matching that fb_id
		PersistenceManager pm = PMF.get().getPersistenceManager();
		AEuser user = pm.getObjectById(AEuser.class, facebook_user.getId());

		UserAppData uad = pm.getObjectById(UserAppData.class,
				user.GetFacebookID());

		
		
		resp.getWriter().write("printing " + uad.getCompetitions().size() + " compentitions for user id:" + uad.getUser_id() + "\n");
		
		
		resp.getWriter().write(uad.printCompetitions());
		
		/*pm must stay open for calls like UserAppData.getCompetitions to work since competition is a serilaized field 
		 * when loading UserAppData from the datastore this field will be empty and will be filled with it's 
		 * datastore values only on demand. therefore, we close the pm only after retreiving any serialized field 
		 * we need from the datastore. 
		 * */
		pm.close();
		
		
	}
}
